<template>
  <view class="container">
    <view class="close_container" @click="close">
      <image mode="aspectFill" class="close" src="../../static/icon_close.png"></image>
    </view>
    <!-- 相机预览 -->
    <view class="camera_container">
      <camera mode="" v-if="showCamera" :flash="flash" :device-position="cameraPosition" class="camera"
        output-dimension="360P" resolution="low" frame-size="small">
      </camera>
    </view>


    <!-- 操作按钮 -->
    <view class="action-buttons">
      <image class="option"
        :src="flash=='on'?'../../static/inspection/icon_exposure.png':'../../static/inspection/icon_exposure_no.png'"
        @click="toggleFlash"></image>
      <image class="camera_button" src="../../static/inspection/icon_shutter.png" @click="takePhoto"></image>
      <image class="option" src="../../static/inspection/icon_refresh.png" @click="toggleCamera"></image>

    </view>


    <!-- 预览区域 -->
    <nut-popup v-model:visible="showPreview" position="bottom" z-index="999">
      <view class="preview-container">
        <view class="close_container" @click="reTake">
          <image mode="aspectFill" class="close" src="../../static/icon_close.png"></image>
        </view>
        <view class="preview-wrap">
          <image :src="photoPath" mode="aspectFit" class="preview-image"></image>
        </view>

        <!-- 水印设置 -->
        <view class="watermark-controls">

          <button class="button_normal" @click="reTake">重新拍摄</button>
          <button class="button_normal" @click="doUse">保存图片</button>
        </view>

        <!-- 隐藏的canvas用于处理图片 -->
        <canvas canvas-id="watermarkCanvas" class="hidden-canvas" :hidpi="false"
          :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px'}"></canvas>
      </view>
    </nut-popup>

  </view>
</template>

<script setup lang="ts">
  import {
    ref
  } from 'vue'
  import {
    onLoad
  } from '@dcloudio/uni-app'

  import {
    uploadFilePromise
  } from '@/utils/upload';
  import Func from '@/utils/func';

  const canvasWidth = ref(300); // 动态宽度
  const canvasHeight = ref(300); // 动态高度
  const showPreview = ref(false)
  // 状态管理
  const showCamera = ref(true)
  const photoPath = ref('')
  const positionIndex = ref(3)
  const watermarkPositions = ['左上', '右上', '左下', '右下', '居中']
  const tempFilePath = ref('')
  let address = ''
  const canvasCtx = ref()

  const flash = ref('off')
  const cameraPosition = ref('back')
  // 切换摄像头
  const toggleCamera = () => {
    cameraPosition.value = cameraPosition.value === 'back' ? 'front' : 'back';

    // 某些安卓设备需要重新渲染 camera 组件才能生效
    // showCamera.value = false;
    // setTimeout(() => {
    //   showCamera.value = true;
    // }, 100);
  }

  // 闪光灯
  const toggleFlash = () => {
    console.log(flash.value)
    flash.value = flash.value === 'off' ? 'on' : 'off';

    // 某些安卓设备需要重新渲染 camera 组件才能生效
    // showCamera.value = false;
    // setTimeout(() => {
    //   showCamera.value = true;
    // }, 100);
  }
  let devicePixelRatio = 1
  onLoad(() => {
    uni.getSystemInfo({
      success: (res) => {

        devicePixelRatio = res.devicePixelRatio
        console.log(devicePixelRatio)
      }
    })
    uni.getLocation({
      type: 'gcj02',
      success: (res) => {
        console.log(res)
       // 获取当前位置的中文描述
       reginDetail(res.longitude, res.latitude).then((res:any) => {
         console.log(res)
          address = res.address
       })

      }
    })

  })

  const close = () => {
    uni.navigateBack()
  }



  // 拍照
  const takePhoto = () => {
    if (!showCamera.value) {
      uni.showToast({
        title: '请先打开相机',
        icon: 'none'
      })
      return
    }

    // 实际项目中需要使用uni.createCameraContext
    // 这里简化处理，实际应该使用camera组件的API
    // uni.showToast({ title: '实际项目中请使用camera组件API', icon: 'none' })
    // #ifdef MP-WEIXIN
    uni.createCameraContext().takePhoto({
      quality: 'low',
      success(res) {

        // 压缩图片
        uni.compressImage({
          src: res.tempImagePath,
          quality: 50, // 压缩质量，0-100，值越小压缩率越高
          success: (compressRes) => {
            const compressedFilePath = compressRes.tempFilePath;
            // 压缩后的图片
            showPreview.value = true
            showCamera.value = false
            tempFilePath.value = compressedFilePath
            photoPath.value = compressedFilePath
            addWatermark()
          },
          fail: (err) => {
            console.error('压缩失败', err);
          }
        });


      }
    });
    // #endif

  }

  // 从相册选择
  const chooseImage = () => {
    uni.chooseImage({
      count: 1,
      sourceType: ['album', 'camera'],
      success: (res) => {
        showPreview.value = true
        showCamera.value = false
        tempFilePath.value = res.tempFilePaths[0]
        photoPath.value = res.tempFilePaths[0]
        console.log(photoPath.value)
        addWatermark()
      }
    })
  }

  // 改变水印位置
  const changePosition = (e : any) => {
    positionIndex.value = e.detail.value
  }

  // 添加水印
  const addWatermark = () => {
    try {
      if (!tempFilePath.value) {
        uni.showToast({
          title: '请先选择图片',
          icon: 'none'
        })
        return
      }

      uni.showLoading({
        title: '正在添加水印...'
      })
      //  获取图片信息
      uni.getImageInfo({
        src: tempFilePath.value,
        success: function (imgInfo) {
          console.log('imgInfo', imgInfo)
          // 创建canvas上下文
          const ctx = uni.createCanvasContext('watermarkCanvas')

          canvasWidth.value = imgInfo.width / devicePixelRatio; // Canvas 宽度（与显示尺寸一致）

          canvasHeight.value = imgInfo.height / devicePixelRatio; // 按比例计算高度

          // 绘制原始图片（按比例缩放）
          ctx.drawImage(tempFilePath.value, 0, 0, canvasWidth.value, canvasHeight.value);
          // 绘制原始图片
          // ctx.drawImage(tempFilePath.value, 0, 0, imgInfo.width, imgInfo.height)

          // 4. 设置水印样式（带阴影）
          ctx.setFontSize(30 / devicePixelRatio);
          ctx.setFillStyle('rgba(84, 185, 204, 1)'); // 文字颜色（白色半透明）
          ctx.setTextAlign('right');
          // 设置阴影
          ctx.setShadow(2, 2, 4, 'rgba(0, 0, 0, 0.3)'); // 阴影偏移 (x, y, blur, color)
          const storeName = '唐山市红星美凯龙'
          const now = new Date();

          const currentTime = Func.getBeijingTimeISOString()

          // 水印内容
          const watermarkText = [
            `${currentTime}`,
            // `${address}`,
            `${storeName}`,
          ];

          // 绘制三行水印
          const bottom = 20 / devicePixelRatio;
          const right = 10 / devicePixelRatio;
          const lineHeight = 36 / devicePixelRatio;
          const startY = canvasHeight.value - bottom;

          watermarkText.forEach((text, index) => {
            ctx.fillText(
              text,
              canvasWidth.value - right,
              startY - index * lineHeight,
            );
          });

          // 绘制到canvas
          ctx.draw(false, () => {
            setTimeout(() => {
              // 获取带水印的图片
              uni.canvasToTempFilePath({
                canvasId: 'watermarkCanvas',
                quality: 0.5,
                success: (res) => {
                  uni.showToast({
                    title: '水印添加成功',
                    icon: 'none'
                  })
                  console.log(res.tempFilePath)
                  uni.getImageInfo({
                    src: res.tempFilePath,
                    success: (res) => {
                      console.log('imgInfo', res)
                    }
                  })
                  console.log(photoPath.value)
                  photoPath.value = res.tempFilePath


                },
                fail: (err) => {
                  console.error('生成水印图片失败:', err)

                  uni.showToast({
                    title: '水印添加失败',
                    icon: 'none'
                  })
                  reTake()
                }
              }, this)
            }, 300)

          })
        }
      });



    } catch (error) {
      console.error('操作失败:', error);
      uni.showToast({
        title: '操作失败',
        icon: 'error'
      });
    }

  }
  //
  const reTake = () => {
    showPreview.value = false
    showCamera.value = true
  }

  // 点击按钮触发保存
  const saveImage = () => {
    // 1. 检查权限状态（微信/支付宝）
    uni.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.writePhotosAlbum']) { // 微信权限字段
          // 2. 主动申请权限
          uni.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              doSave()
            },
            fail: () => {
              showAuthGuide()
            }
          });
        } else {
          doSave()
        }
      }
    });
  }


  // 权限拒绝后引导用户开启
  const showAuthGuide = () => {
    uni.showModal({
      title: '提示',
      content: '需要相册权限才能保存图片，请前往设置开启',
      confirmText: '去设置',
      success: (res) => {
        if (res.confirm) {
          uni.openSetting(); // 跳转系统设置页
        }
      }
    });
  }
  const doUse = () => {
    //上传
    uni.showLoading({
      title: '上传中...'
    })
    uploadFilePromise(photoPath.value).then((result : any) => {
      uni.showToast({
        title: '上传成功',
        icon: 'none'
      })
      uni.navigateBack()
      console.log(result)
      uni.$emit('wahterRemark', result)
    })
  }
  // 保存图片
  const doSave = () => {
    if (!photoPath.value) {
      uni.showToast({
        title: '没有可保存的图片',
        icon: 'none'
      })
      return
    }

    uni.saveImageToPhotosAlbum({
      filePath: photoPath.value,
      success: () => {
        photoPath.value = ''
        close()
        uni.showToast({
          title: '保存成功'
        })
      },
      fail: (err) => {
        photoPath.value = ''
        console.error('保存失败:', err)
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    })
  }
</script>

<style>
  page {
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: #54B9CC;
  }

  .container {
    height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: relative;
  }

  .camera_container {
    width: 100vw;
    aspect-ratio: 9/16;
    max-height: 82vh;
    margin-top: 80rpx;
    margin-bottom: 20rpx;
  }

  .camera {
    height: 100%;
    width: 100%;

  }

  .action-buttons {
    padding-left: 15rpx;
    padding-right: 15rpx;
    display: flex;
    justify-content: space-around;
    width: 100%;
    align-items: center;
    margin-top: 30rpx;
    margin-bottom: 10rpx;
  }

  .camera_button {
    width: 180rpx;
    height: 180rpx;
  }

  .option {
    width: 60rpx;
    height: 60rpx
  }

  .action-buttons button {
    flex: 1;
    margin: 0 10rpx;
  }

  .preview-container {
    width: 100vw;
    height: 100vh;

    flex-direction: column;
    align-items: center;
    padding-top: 88rpx;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    background-color: #54B9CC;
    position: relative;
  }

  .preview-wrap {
    aspect-ratio: 9/16;
    max-height: 82vh;
    display: flex;
    justify-content: center;
    width: 100%;
  }

  .preview-image {
    height: 100%;
    width: 100%;
  }

  .watermark-controls {
    margin-top: 40rpx;
    width: 100vw;
    display: flex;
    justify-content: space-around;
    flex-direction: row;
    margin-bottom: 40rpx;
  }

  .watermark-input {
    border: 1px solid #eee;
    padding: 10rpx;
    border-radius: 8rpx;
  }

  .hidden-canvas {
    position: fixed;
    top: 0px;
    left: -9999px;
    width: 100vw;
    height: 100vh;
  }

  .button_normal {
    width: 45%;
    color: white;
    font-size: 32rpx;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    border: 2rpx solid white;
    background-color: #54B9CC;
  }

  .close_container {
    width: 64rpx;
    height: 64rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 32rpx;
    padding: 5rpx;
    background: rgba(0, 0, 0, 0.15);
    position: absolute;
    left: 32rpx;
    top: 132rpx;
    z-index: 100;
    overflow: hidden;
  }

  .close {
    width: 42rpx;
    height: 42rpx;
    margin-right: 6rpx;

  }
</style>
